package com.tao.plan.common.utils;


import com.nlf.calendar.Lunar;
import com.nlf.calendar.Solar;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class DateUtil {

	/**
	 * 获取当前日期到指定日期的差值
	 * 如果这一年已经经过了指定日期，则获取与当前年份的下一年的指定日期的差值
	 * isLunar 指的是 targetTime 是农历时间还是公历时间
	 */
	public static Integer getNextDays(LocalDateTime targetTime, boolean isLunar) {
		LocalDate now = LocalDate.now();
		if (isLunar) {
			// 农历逻辑
			// 将农历日期转换为公历日期
			LocalDate solarDate = convertLunarToSolar(targetTime.toLocalDate());
			// 计算下一年的农历日期对应的公历日期
			LocalDate nextSolarDate = convertLunarToSolar(solarDate.plusYears(1));
			// 判断是否已经过了今年的指定日期
			if (now.isAfter(solarDate)) {
				return (int) ChronoUnit.DAYS.between(now, nextSolarDate);
			} else {
				return (int) ChronoUnit.DAYS.between(now, solarDate);
			}
		} else {
			// 公历逻辑
			LocalDate targetDate = targetTime.toLocalDate();
			// 计算下一年的公历日期
			LocalDate nextYearDate = targetDate.withYear(now.getYear() + 1);
			// 判断是否已经过了今年的指定日期
			if (now.isAfter(targetDate)) {
				return (int) ChronoUnit.DAYS.between(now, nextYearDate);
			} else {
				return (int) ChronoUnit.DAYS.between(now, targetDate);
			}
		}
	}

	/**
	 * 当前日期和指定日期的差值（距离第一次）
	 */
	public static Integer getFirstDays(LocalDateTime targetTime, boolean isLunar) {
		LocalDate now = LocalDate.now();
		if (isLunar) {
			// 农历逻辑
			// 将农历日期转换为公历日期
			LocalDate solarDate = convertLunarToSolar(targetTime.toLocalDate());
			// 计算差值
			return -(int) ChronoUnit.DAYS.between(now, solarDate);
		} else {
			// 公历逻辑
			// 直接计算差值
			return  -(int) ChronoUnit.DAYS.between(now, targetTime.toLocalDate());
		}
	}

	/**
	 * 将农历日期转换为公历日期
	 */
	public static LocalDate convertLunarToSolar(LocalDate lunarDate) {
		// 使用 lunar-java 库将农历日期转换为公历日期
		Lunar lunar = new Lunar(lunarDate.getYear(), lunarDate.getMonthValue(), lunarDate.getDayOfMonth());
		Solar solar = lunar.getSolar();
		return LocalDate.of(solar.getYear(), solar.getMonth(), solar.getDay());
	}

	public static void main(String[] args) {
		// 测试
		LocalDateTime targetTime = LocalDateTime.of(2025, 2, 28, 0, 0);
		boolean isLunar = false; // 假设是农历
		System.out.println("Next Days: " + getNextDays(targetTime, isLunar));
		System.out.println("First Days: " + getFirstDays(targetTime, isLunar));
	}


}
